import React, { useState, useCallback, useEffect } from 'react';
import { getSysDepartmentFindList } from '../../../../../Api/listUrl'
import {getSofActRuleFindCas, putSofActRuleInsertFlow, getSofActRuleUpdateEcho, postSofActRuleUpdateFlow} from '../../../api'

import { Modal, Form, Input, message, Select, Radio, InputNumber, Button, Cascader } from 'antd'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

const { Option } = Select;

/**
 * @description: 生产总线设置-添加生产总线
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-08-05）字段修改
 */

const AddProductionPlanSetModule = ({ addProductionPlanSetModuleShow, setAddProductionPlanSetModuleShow, clickId, listFun, setClickId }) => {
    const [form] = Form.useForm()
    const {validateFields, resetFields, setFieldsValue}  = form
    const [departmentList, setDepartmentList] = useState([])
    const [flowList, setFlowList] = useState([])
    const flowFun = useCallback(
        () => {
            ;(async () => {
                const {code, msg, data} = await getSofActRuleFindCas()
                if(code === '20000') {
                    setFlowList(data)
                }else{
                    message.error(msg)
                }
            })()
        },
        [],
    )
    const departmentFun = useCallback(
        () => {
            ; (async () => {
                const { code, msg, data } = await getSysDepartmentFindList()
                if (code === '20000') {
                    setDepartmentList(data)
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    const changeShow = useCallback(
        () => {
            if(clickId) {
                ;(async () => {
                    const {code, msg, data} = await getSofActRuleUpdateEcho({id: clickId})
                    if(code === '20000') {  
                        setFieldsValue(data)
                    }else{
                        message.error(msg)
                    }
                })()
            }
        },
        [clickId, setFieldsValue],
    )
    useEffect(() => {
        departmentFun()
        flowFun()
        changeShow()
    }, [departmentFun, flowFun, changeShow])
    const handleOk = () => {
        validateFields().then(values => {
            if(values.blockId) {
                let blockIdArr = []
                values.blockId.forEach(element => {
                    blockIdArr.push(element[element.length -1])
                });
                values.blockId = blockIdArr
            }
            if(values.parentId) {
                values.parentId = values.parentId[values.parentId.length -1]
            }
            if(clickId) {
                values.id = clickId
                ;(async () => {
                    const {code, msg} = await postSofActRuleUpdateFlow(values)
                    if(code === '20000') {
                        message.success('编辑成功！')
                        setClickId(undefined)
                        resetFields()
                        listFun()
                        setAddProductionPlanSetModuleShow(false)
                    }else{
                        message.error(msg)
                    }
                })()
            }else{
                ;(async () => {
                    const {code, msg} = await putSofActRuleInsertFlow(values)
                    if(code === '20000') {
                        message.success('添加成功！')
                        resetFields()
                        listFun()
                        setAddProductionPlanSetModuleShow(false)
                    }else{
                        message.error(msg)
                    }
                })()
            }

        })
    };

    const handleCancel = () => {
        setClickId(undefined)
        resetFields()
        setAddProductionPlanSetModuleShow(false);
    };
    return <Modal title={clickId ? "编辑总线" : "添加总线"} visible={addProductionPlanSetModuleShow} onOk={handleOk} onCancel={handleCancel}>
        <Form
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            form = {form}
        >
            <Form.Item
                label="规则名称"
                name="flowName"
                rules={[{ required: true, message: '请输入规则名称!' }]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="父流程"
                name="parentId"
            >
                <Cascader changeOnSelect options={flowList} fieldNames = {{ label: 'flowName', value: 'id', children: 'children' }}  placeholder="请选择父流程！" />
            </Form.Item>
            <Form.List
                name="blockId"
            >
                {(fields, { add, remove }, { errors }) => (
                    <>
                        {fields.map((field, index) => (
                            <Form.Item
                                {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                                label={index === 0 ? '管理阻塞' : ''}
                                required={false}
                                key={field.key}
                            >
                                <Form.Item
                                    {...field}
                                    validateTrigger={['onChange', 'onBlur']}
                                    rules={[
                                        {
                                            required: true,
                                            message: "请选择管理阻塞",
                                        },
                                    ]}
                                    noStyle
                                >
                                     <Cascader changeOnSelect style = {{width : '60%'}} options={flowList} fieldNames = {{ label: 'flowName', value: 'id', children: 'children' }}  />
                                </Form.Item>
                                <MinusCircleOutlined
                                    className="dynamic-delete-button"
                                    onClick={() => remove(field.name)}
                                />
                            </Form.Item>
                        ))}
                        <Form.Item >
                            <Button
                                type="dashed"
                                onClick={() => add()}
                                style={{ width: '100%' }}
                                icon={<PlusOutlined />}
                            >
                                添加管理阻塞
                            </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>
            <Form.Item
                label="执行部门"
                name="departmentId"
                rules={[{ required: true, message: '请选择执行部门!' }]}
            >
                <Select style={{ width: 120 }} >
                    {
                        departmentList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                    }

                </Select>
            </Form.Item>
            <Form.Item
                label="执行顺序"
                name="order"
                rules={[{ required: true, message: '请输入执行顺序!' }]}
            >
                <InputNumber />
            </Form.Item>
            <Form.Item
                label="状态"
                name="state"
                rules={[{ required: true, message: '请选择状态！' }]}
            >
                <Radio.Group >
                    <Radio value={0}>开启</Radio>
                    <Radio value={1}>关闭</Radio>
                </Radio.Group>
            </Form.Item>
        </Form>
    </Modal>
}
const formItemLayoutWithOutLabel = {
    wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 16, offset: 8 },
    },
};

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
    },
};

export default AddProductionPlanSetModule